<template>
  <div class="login-setting">
    <el-form ref="settingForm" :model="userInfo" :rules="rules" label-width="80px">
      <el-form-item label="姓名：" prop="username">
        <el-input v-model="userInfo.username" width="200px" />
      </el-form-item>
      <el-form-item label="新密码：" prop="password">
        <el-input v-model="userInfo.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">更新</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { saveUserDetailByIdAPI, getUserDetailByIdAPI } from '@/api'
export default {
  data() {
    return {
      // 保存数据，用于显示和提交
      userInfo: {
        username: '',
        password: ''
      },
      // 表单验证规则
      rules: {
        username: [{ required: true, message: '用户名不能为空', triggler: 'blur' }],
        password: [{ required: true, message: '密码不能为空', triggler: 'blur' }]
      }
    }
  },
  created() {
    this.loadUserDetailById()
  },
  methods: {
    // 更新点击按钮
    onSubmit() {
      // 点击确认的时候进行兜底校验
      this.$refs.settingForm.validate(async valide => {
        if (valide) {
          // 进行逻辑业务代码
          if (!valide) return this.$message.error('请检查用户名和密码')
          // 请求修改
          const res = await saveUserDetailByIdAPI(this.userInfo)
          // 提交失败显示失败原因
          if (!res.success) return this.$message.error(res.message)
          this.loadUserDetailById()
          // 跳转到当前页面，实现强制刷新
          this.$router.go(0)
          this.$message.success(res.message)
        }
      })
    },
    // 获取该员工数据(进行数据双向绑定，进入页面时显示数据)
    async loadUserDetailById() {
      const res = await getUserDetailByIdAPI(this.$route.query.id).catch(err => err)
      if (!res.success) return this.$message.error(res.message)
      // 将数据保存
      this.userInfo = res.data
    }
  }
}
</script>
<style lang="scss" scoped>
 .login-setting {
    width: 450px;
    margin-top: 30px;
    margin-left: 160px;
  }
</style>
